package com.zhsj.OkeHomeConsumption.ui.activity;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapException;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.maps2d.model.NaviPara;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.RestaurantBean;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 商铺详情地图页面
 */
public final class RestaurantMapActivity extends MyActivity implements LocationSource, AMapLocationListener
        , PoiSearch.OnPoiSearchListener, AMap.OnMyLocationChangeListener, GeocodeSearch.OnGeocodeSearchListener, AMap.InfoWindowAdapter, AMap.OnMapClickListener,
        AMap.OnMapLongClickListener, AMap.OnCameraChangeListener {

    MapView map;


    @BindView(R.id.ren_sure)
    RelativeLayout renSure;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.city_text)
    TextView cityText;


    //初始化地图控制器对象
    private AMap aMap;

    private MyLocationStyle myLocationStyle;

    private OnLocationChangedListener mListener;

    private ImageView nack_img;

    // 选择的地址
    private String chooseAddress = "";

    private String city = "";//搜索城市

    private Marker marker;

    private LatLonPoint latLonPoint;

    private String keyWord;

    private MarkerOptions markerOption;

    private LatLng latlng;

    private int Page = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private List<PoiItem> poiItems;// poi数据
    private LatLonPoint lp;//


    private double latitude = 0;//纬度

    private double longitude = 0;//经度

    private String name = "";

    private RestaurantBean restaurantBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shangpu_map;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_copy_title;
    }

    @Override
    protected void initView() {
        nack_img = findViewById(R.id.nack_img);
        map = findViewById(R.id.map);
        if (aMap == null) {
            aMap = map.getMap();
        }
        restaurantBean = (RestaurantBean) getIntent().getSerializableExtra("bean");
    }

    @Override
    protected void initData() {

        latitude = restaurantBean.getLatitude();
        longitude = restaurantBean.getLongitude();
        titleText.setText(restaurantBean.getShopName());
        cityText.setText(restaurantBean.getAddress()+"    "+ distanceFormat(restaurantBean.getDistanceMeter()));
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点，用于满足只想使用定位，不想使用定位小蓝点的场景，设置false以后图面上不再有定位蓝点的概念，但是会持续回调位置信息。

        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(17);
        aMap.moveCamera(mCameraUpdate);
        aMap.setOnMyLocationChangeListener(this);

        renSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAMapNavi(marker);
            }
        });
        addMarkersToMap();
        nack_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap() {
            latlng = new LatLng(latitude, longitude);
            markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                    .position(latlng)
                    .title("s")
                    .snippet(name)
                    .draggable(true);
        marker = aMap.addMarker(markerOption);
        aMap.addMarker(markerOption);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        //在activity执行onCreate时执行map.onCreate(savedInstanceState)，创建地图
        map.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行map.onDestroy()，销毁地图
        map.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行map.onResume ()，重新绘制加载地图
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行map.onPause ()，暂停地图的绘制
        map.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行map.onSaveInstanceState (outState)，保存地图当前的状态
        map.onSaveInstanceState(outState);
    }

    //获取经纬度信息
    @Override
    public void onMyLocationChange(Location location) {


    }

    //通过经纬度查找地址的回调方法
    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    /**
     * 对单击地图事件回调
     */
    @Override
    public void onMapClick(LatLng latLng) {

    }


    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 对正在移动地图事件回调
     */
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    /**
     * 对移动地图结束事件回调
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    /**
     * 对长按地图事件回调
     */
    @Override
    public void onMapLongClick(LatLng latLng) {

    }

    /**
     * 移动镜头到当前的视角。
     *
     * @since V2.1.0
     */
    public void zoomToSpan(LatLngBounds.Builder bounds) {

        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 100));
    }

    /**
     * 调起高德地图导航功能，如果没安装高德地图，会进入异常，可以在异常中处理，调起高德地图app的下载页面
     */
    public void startAMapNavi(Marker marker) {
        // 构造导航参数
        NaviPara naviPara = new NaviPara();
        // 设置终点位置
        naviPara.setTargetPoint(marker.getPosition());
        // 设置导航策略，这里是避免拥堵
        naviPara.setNaviStyle(AMapUtils.DRIVING_AVOID_CONGESTION);

        // 调起高德地图导航
        try {
            AMapUtils.openAMapNavi(naviPara, getApplicationContext());
        } catch (AMapException e) {

            // 如果没安装会进入异常，调起下载页面
            AMapUtils.getLatestAMapApp(getApplicationContext());

        }

    }
    /**
     * 距离只保留两位小数
     *
     * @param distance 以米为单位
     * @return
     */
    public static String distanceFormat(double distance) {
        String str;
        double value = distance;
        if (distance >= 1000) {
            value = value / 1000;
            str = "KM";
        } else {
            str = "M";
        }
        return value + str;
    }

}